package com.yugao.fintech.antelope.base.model.module.tenant;

import com.yugao.fintech.antelope.base.model.module.auth.AuthUserTenant;
import com.yugao.fintech.framework.assistant.utils.StringUtils;
import lombok.Getter;

import java.util.Objects;

/**
 * 工作空间上下文

 */

public class TenantContext {
    public static final Long EMPTY_TENANT_ID = -1L;
    /**
     * 当前租户id
     */
    @Getter
    private Long tenantId;

    /**
     * 主租户id
     */
    @Getter
    private Long mainTenantId = -1L;

    @Getter
    private boolean isFilterTenant = true;

    /**
     * 是否过滤主租户
     */
    @Getter
    private boolean isFilterMainTenant = true;

    public TenantContext filterTenant(boolean filterTenant) {
        isFilterTenant = filterTenant;
        return this;
    }

    public TenantContext filterMainTenant(boolean isFilter) {
        isFilterMainTenant = isFilter;
        return this;
    }

    public TenantContext setTenantId(String tenantId) {
        tenantId = isValidTenantId(tenantId) ? tenantId : "";
        tenantId = StringUtils.defaultIfEmpty(tenantId, "-1");
        this.tenantId = Long.parseLong(tenantId);
        return this;
    }

    public boolean isValidTenantId(String tenantId) {
        return !(StringUtils.isEmpty(tenantId) || "null".equals(tenantId) || "undefined".equals(tenantId) || "-1".equals(tenantId));
    }

    public void setMainTenantId(Long mainTenantId) {
        this.mainTenantId = mainTenantId;
    }

    public void setMainTenantId(String mainTenantId) {
        mainTenantId = isValidTenantId(mainTenantId) ? mainTenantId : "";
        this.mainTenantId = Long.parseLong(StringUtils.defaultIfEmpty(mainTenantId, "-1"));
    }

    public TenantContext setTenantId(Long tenantId) {
        this.tenantId = tenantId;
        return this;
    }

    public void setTenant(AuthUserTenant tenant) {
        if (Objects.isNull(tenant)) {
            return;
        }
        this.tenantId = tenant.getTenantId();
        this.mainTenantId = tenant.getMainTenantId();
    }
}
